package com.suning.framework;

import com.suning.framework.utils.EsUtils;
import net.sf.json.JSONObject;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.*;

/**
 * 〈一句话功能简述〉<br>
 * 〈功能详细描述〉
 *
 * @author 16080951(林健)
 * @Copyright (c) 2016 苏宁软件技术有限公司 版权所有
 * @see [相关类/方法]（可选）
 * @since [产品 /模块版本] （可选）
 */
public class Test {

    //索引
    private final static String INDEX = "ficdms.mps.member";

    //类型
    private final static String TYPE = "portait";

    private static Test test = new Test();

    /**
     * 存es
     * XPOST 'localhost:9200/xxx/_bulk?pretty' -d '{}'
     *
     * @param mpsMemberInfo the mps member info
     */
    public void setInfo(List<Mps_member_portrait_info> mpsMemberInfo){

        Client client = EsUtils.openConnection();
        BulkRequestBuilder bulkRequest = client.prepareBulk();
        for (Mps_member_portrait_info mpsObject: mpsMemberInfo) {
            bulkRequest.add(
                    client.prepareIndex("ficdms.mps.member","portait",mpsObject.getAcct_no()).setSource(JSONObject.fromObject(mpsObject).toString())
            );

        }

        BulkResponse bulkResponse = bulkRequest.execute().actionGet();
        if (bulkResponse.hasFailures()) {
            //处理错误
            System.out.println("处理错误！！！");
        }

        client.close();

    }

    /**
     * 添加数据到ES
     */
    private static void doAdd() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("config/application.xml");
        //获取dao
        Dao dao = (Dao) applicationContext.getBean("dao");

        //查询100条数据
        List<Mps_member_portrait_info> result = dao.query();
        System.out.println(result);
        //放入es
        test.setInfo(result);
    }


    /**
     * 分页查询
     */
    public static List<Mps_member_portrait_info> doPageQuery(){
        Client client = EsUtils.openConnection();

        //每页多少条
        long pageSize = 100;

        //匹配查询,配合.setQuery(queryBuilder)
        QueryBuilder queryBuilder = new MatchQueryBuilder("acct_no","0000000000033171278");
        //QueryBuilder queryBuilderMap = new HasParentQueryBuilder("acct_no","0000000000033171278");
        //QueryBuilder queryBuilderMap = new HasChildQueryBuilder("acct_no","0000000000033171278");
        //只显示acct_no
        //setSource("acct_no");;

        //当更新更新冲突时，重试次数。
        //client.prepareUpdate().setRetryOnConflict();

        //多个搜索一个请求过去。
        //client.prepareMultiSearch()
        SearchResponse searchResponse =
                client.prepareSearch(INDEX)
                        .setSearchType(SearchType.DFS_QUERY_AND_FETCH)
                        .setQuery(queryBuilder)
                        .setScroll(TimeValue.timeValueMinutes(1))
                        .setSize((int)pageSize / 5) //返回条数 = 分片数 * size
                        .execute()
                        .actionGet();


        //总量
        long total = searchResponse.getHits().getTotalHits();
        System.out.println("total : " + total);

        //共多少页
        long totalPage = ( total % pageSize == 0 ) ? total / pageSize : (total / pageSize)+1;

        //当前页
        long currentPage = 1;
        List<SearchHit> result = new ArrayList<SearchHit>();
        while (true) {
            searchResponse = client.prepareSearchScroll(searchResponse.getScrollId())
                    .setScroll(TimeValue.timeValueMinutes(1))
                    .execute()
                    .actionGet();

            if(searchResponse.getHits().hits().length == 0)break;
            else{
                //将所有数据放入List
                Iterator<SearchHit> iterator = searchResponse.getHits().iterator();
                while(iterator.hasNext()){
                    SearchHit hit = iterator.next();
                    result.add(hit);
                }

                if(result.size() > 10000) break;
            }
        }

        //当前result中的总数据量
        System.out.println(result.size());

        //分页取数据
        for(int i = 0 ; i < totalPage && currentPage <= totalPage ;i++ ){

            List _tmp = result.subList((int)((currentPage - 1)*pageSize),(int)((currentPage * pageSize > total ? total : currentPage * pageSize)));
            System.out.println(_tmp);
            currentPage++;

        }

        /*for(SearchHit obj : result){
            String json = obj.getSourceAsString();
            //System.out.println(json);
        }*/




        client.close();
        return null;
    }





    /**
     * The entry point of application.
     *
     * @param args the input arguments
     */
    public static void main(String[] args) {

        //添加数据到ES
        doAdd();

        //模拟分页数据查询
        //doPageQuery();
    }


}
